# -*- coding: utf-8 -*-

from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.core.mail.message import EmailMessage
from django.http import HttpResponseRedirect, HttpRequest
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from index import needAuthForm
from users.models import AccountActivation, UserProfile
import base64
import hashlib
import random
import settings
import string


def show(request):
    """ initialize function """
    user = request.user
    if user.is_anonymous() == True:
        return HttpResponseRedirect('/home/')
    else:
        # print('no GET, no logout %s', user.username))
        return render_to_response('template_User.html',
                              context_instance=RequestContext(request)
                              )
        
def verify(request):
    user = request.user
    sendActivationMail(request, user.email, user.username)
    return HttpResponseRedirect('/user/')

def logoutuser(request):
    logout(request)
    return HttpResponseRedirect('/home/')

def activate(request, actKey, actCode):
    try:
        ins = AccountActivation.objects.get(key=actKey, code=actCode)
    except AccountActivation.DoesNotExist:
        return render_to_response('template_InvalidActivationLink.html',
                                  needAuthForm(),
                                  context_instance=RequestContext(request)
                                  )
        
    if ins.activated == True:
        return HttpResponseRedirect('/user/')
    
    user = get_user_from_actLink(request, ins)
    if user is None:
        return render_to_response('template_InvalidActivationLink.html',
                                  needAuthForm(),
                                  context_instance=RequestContext(request)
                                  )
    else:
        ins.activated = True
        user.is_active = True
        ins.save()
        user.save()
        
        return HttpResponseRedirect('/user/')
        
def get_user_from_actLink(request, aam):
    """ return None if can't get user from either request.user or User model """
    user = request.user
    if user is not None:
        if user.is_anonymous() == False:
            return user
    user = User.objects.get(username=aam.username)
    return user



def generate_activate_code(email):
    key = generate_hash_from_mail(email)
    code = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(random.randint(8,16)))
    return key, code

def generate_hash_from_mail(email):
    m = hashlib.md5( email.join("labor insurance") )
    s = base64.urlsafe_b64encode(m.hexdigest()).rstrip('=')
    # length = 28
    return s[:12] + s[14:17] + s[18:31]

def sendActivationMail(request, mailAddres, username):
    """ send activataion mail """
    actKey, actCode = generate_activate_code(mailAddres)
    AccountActivation.objects.create(key=actKey, code=actCode, username=username)
    
    secure = ''
    if HttpRequest.is_secure(request):
        secure = 's'
    
    actLink = 'http{sec}://{host}/user/confirm_email/{key}/{code}/'.format(sec=secure, host=HttpRequest.get_host(request), key=actKey, code=actCode)
    
    emailSubject = _('Welcom to 5krun')
    
    emailBody = _('Dear user,\nWelcome to join 5krun.\nPlease click following link to active your account.\n')
    emailBody += str(actLink)
    
    email = EmailMessage(subject=emailSubject,
                         body=emailBody,
                         from_email= settings.DEFAULT_FROM_EMAIL,
                         #to=['to1@example.com', 'to2@example.com'], bcc=['bcc@example.com'],
                         #headers = {'Reply-To': 'another@example.com'}
                         to=[mailAddres],
                         )
    email.send(fail_silently=False)
    
def maskPid(pid):
    strlen = len(pid)
    if strlen == 0 : return pid
    
    partlen = strlen / 3
    
    if partlen <= 2:
        result = '' + pid[strlen-1:strlen].rjust(strlen, '*')
    else:
        result = '' + pid[strlen-4:strlen].rjust(strlen, '*')
    return result
